import { request } from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 地址信息接口
 */
export interface Address {
  address_id: string
  receiver_name: string
  receiver_mobile: string
  province: string
  city: string
  district: string
  detailed_address: string
  is_default: boolean
  create_time: string
  update_time: string
}

/**
 * 创建/更新地址参数接口
 */
export interface AddressParams {
  receiver_name: string
  receiver_mobile: string
  province: string
  city: string
  district: string
  detailed_address: string
  is_default?: boolean
}

/**
 * 地址列表响应接口
 */
export interface AddressListResponse {
  count: number
  next: string | null
  previous: string | null
  results: Address[]
}

// ==================== API 服务 ====================

/**
 * 地址API服务
 */
export const addressApi = {
  /**
   * 获取地址列表
   * GET /auth/addresses/
   */
  getAddressList(): Promise<AddressListResponse> {
    console.log('开始调用 getAddressList API')
    return request.get<Address[]>('/auth/addresses/').then((response) => {
      console.log('getAddressList API 响应:', response)
      // 直接返回响应拦截器构造的 AddressListResponse 对象
      return response as unknown as AddressListResponse
    })
  },

  /**
   * 获取默认地址
   * GET /auth/addresses/default/
   */
  getDefaultAddress(): Promise<Address> {
    return request.get<Address>('/auth/addresses/default/').then((response) => response.data)
  },

  /**
   * 创建地址
   * POST /auth/addresses/
   * @param params - 地址参数
   */
  createAddress(params: AddressParams): Promise<Address> {
    return request.post<Address>('/auth/addresses/', params).then((response) => response.data)
  },

  /**
   * 更新地址
   * PUT /auth/addresses/{address_id}/
   * @param address_id - 地址ID
   * @param params - 地址参数
   */
  updateAddress(address_id: number, params: AddressParams): Promise<Address> {
    return request
      .put<Address>(`/auth/addresses/${address_id}/`, params)
      .then((response) => response.data)
  },

  /**
   * 删除地址
   * DELETE /auth/addresses/{address_id}/
   * @param address_id - 地址ID
   */
  deleteAddress(address_id: number): Promise<any> {
    return request.delete<any>(`/auth/addresses/${address_id}/`).then((response) => response.data)
  },

  /**
   * 设置默认地址
   * POST /auth/addresses/{address_id}/set_default/
   * @param address_id - 地址ID
   */
  setDefaultAddress(address_id: number): Promise<any> {
    return request
      .post<any>(`/auth/addresses/${address_id}/set_default/`)
      .then((response) => response.data)
  },
}

// ==================== 工具函数 ====================

/**
 * 格式化地址显示
 */
export const formatAddress = (address: Address): string => {
  return `${address.province}${address.city}${address.district}${address.detailed_address}`
}

/**
 * 验证手机号
 */
export const validateMobile = (mobile: string): boolean => {
  const mobileRegex = /^1[3-9]\d{9}$/
  return mobileRegex.test(mobile)
}

// ==================== 默认导出 ====================

export default addressApi
